<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="路线编号" prop="routeId">
        <el-input
            v-model="queryParams.routeId"
            placeholder="请输入路线编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="社区ID" prop="communityId">
        <el-input
            v-model="queryParams.communityId"
            placeholder="请输入社区ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="巡检人姓名" prop="patrollerName" label-width="100px">
        <el-input
            v-model="queryParams.patrollerName"
            placeholder="请输入巡检人姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="巡检人手机号" prop="patrollerPhone" label-width="120px">
        <el-input
            v-model="queryParams.patrollerPhone"
            placeholder="请输入巡检人手机号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="巡检时间" prop="patrolTime">
        <el-date-picker clearable
                        v-model="queryParams.patrolTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择巡检时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="巡更结果" prop="patrolResult">
        <el-select v-model="queryParams.patrolResult"
                   placeholder="请选择巡更结果"
                   style="width: 180px;">
          <el-option label="完成" value="完成"/>
          <el-option label="未完成" value="未完成"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:patrol:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:patrol:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:patrol:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:patrol:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading"
              :data="patrolList"
              @selection-change="handleSelectionChange"
              :row-style="{ height: '100px', lineHeight: '100px' }">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编号" align="center" prop="patrolId"/>
      <el-table-column label="路线编号" align="center" prop="routeId"/>
      <el-table-column label="社区" align="center" prop="communityId" :formatter="formatCommunityName"/>
      <el-table-column label="巡检人姓名" align="center" prop="patrollerName"/>
      <el-table-column label="巡检人手机号" align="center" prop="patrollerPhone"/>
      <el-table-column label="巡检时间" align="center" prop="patrolTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.patrolTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="巡更结果" align="center" prop="patrolResult"/>
      <el-table-column label="图片(JSON数组)" align="center" width="200" prop="images">

        <template #default="scope">
          <img :src="scope.row.images" style="width: 100px; height: 100px">
        </template>
      </el-table-column>
      <el-table-column label="状态"
                       align="center"
                       prop="status"
                       width="100"
                       :filters="[{
                           text: '无异常',
                           value: 1
                       }, {
                           text: '异常',
                           value: 0
                       }]"
                       :filter-method="filterTag"
                       filter-placement="bottom-end">
        <template #default="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">
            {{ scope.row.status == 1 ? '无异常' : '异常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:patrol:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:patrol:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改patrol对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="patrolRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="路线ID" prop="routeId" label-width="100px">
         <el-select label="路线ID" v-model="form.routeId" placeholder="请选择路线ID">
           <el-option label="1" value="1"/>
           <el-option label="2" value="2"/>
           <el-option label="3" value="3"/>
           <el-option label="4" value="4"/>
         </el-select>
        </el-form-item>
        <el-form-item label="社区ID" prop="communityId">
          <el-select label="社区ID" v-model="form.communityId" placeholder="请选择社区ID">
            <el-option label="阳光花园" value="1"/>
            <el-option label="绿城雅苑" value="2"/>
            <el-option label="山水名都" value="3"/>
            <el-option label="枫林壹号" value="4"/>
            <el-option label="湖园家园" value="5"/>
          </el-select>
        </el-form-item>
        <el-form-item label="巡检人姓名" prop="patrollerName" label-width="100px">
          <el-input v-model="form.patrollerName" placeholder="请输入巡检人姓名"/>
        </el-form-item>
        <el-form-item label="巡检人手机号" prop="patrollerPhone" label-width="100px">
          <el-input v-model="form.patrollerPhone" placeholder="请输入巡检人手机号"/>
        </el-form-item>
        <el-form-item label="巡检时间" prop="patrolTime" label-width="100px">
          <el-date-picker clearable
                          v-model="form.patrolTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择巡检时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="巡更结果" prop="patrolResult" label-width="100px">
          <el-radio-group v-model="form.patrolResult">
            <el-radio label="完成">完成</el-radio>
            <el-radio label="未完成">未完成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-model="form.images" label="图片(JSON数组)" prop="images" label-width="120px">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/system/patrol/uploadminio"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="{
                'Authorization': 'Bearer ' + getToken()
              }"
              name="file"
          >
            <img v-if="form.images" :src="form.images" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status" label-width="100px">
          <el-radio-group v-model="form.status">
            <el-radio label="1">无异常</el-radio>
            <el-radio label="0">异常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description" label-width="100px">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>


</template>


<script setup name="Patrol">
import {listPatrol, getPatrol, delPatrol, addPatrol, updatePatrol} from "@/api/system/patrol"
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {getToken} from "@/utils/auth"


const queryRef = ref(null);  // 对应查询区的 <el-form ref="queryRef">
const patrolRef = ref(null); // 对应对话框的 <el-form ref="patrolRef">
const {proxy} = getCurrentInstance()
const patrolList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")


const communityDict = {
  1: '阳光花园',
  2: '绿城雅苑',
  3: '山水名都',
  4: '枫林壹号',
  5: '湖畔家园'
};

// 单独定义格式化方法（与其他方法同级）
const formatCommunityName = (row) => {
  // 注意：row.communityId 可能是字符串类型，需转数字匹配字典键
  return communityDict[Number(row.communityId)] || row.communityId;
};



const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    routeId: null,
    communityId: null,
    patrollerName: null,
    patrollerPhone: null,
    patrolTime: null,
    patrolResult: null,
    images: null,
    status: null,
    description: null,
  },
  rules: {}
})


const beforeAvatarUpload = (rawFile) => {
  const isJpgOrPng = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
  if (!isJpgOrPng) {
    ElMessage.error('仅支持 JPG/PNG 格式！');
    return false;
  }
  const isLt2M = rawFile.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！');
    return false;
  }
  return true;
};


const handleAvatarSuccess = (response) => {
  if (response.code === 200 || response.success === true) {
    // 适配后端返回的数据结构

    form.value.images = response.msg; // 预览图赋值


    console.log(response.msg)
    console.log(data.form)

    ElMessage.success('上传成功！');
  } else {
    ElMessage.error('上传失败：' + (response.msg || '未知错误'));
  }
};


const {queryParams, form, rules} = toRefs(data)

const filterTag = (value, row) => {
  return row.status === value
}


/** 查询patrol列表 */
function getList() {
  loading.value = true
  listPatrol(queryParams.value).then(response => {
    patrolList.value = response.rows
    total.value = response.total
    console.log(patrolList.value)
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  reset()
  console.log(form.value)
  open.value = false
}

// 表单重置
function reset() {

  console.log(form.value)
  // 1. 重置表单数据为初始值
  form.value = {
    patrolId: null,
    routeId: null,
    communityId: null,
    patrollerName: null,
    patrollerPhone: null,
    patrolTime: null,
    patrolResult: null,
    status: null,
    images: null,
    description: null,
    createTime: null,
    updateTime: null
  };
  // 2. 重置表单校验状态（必须通过 ref 调用 resetFields()）
  if (patrolRef.value) {
    patrolRef.value.resetFields();
  }
  // // 3. 清空图片预览
  // form.value.images = '';
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {

  form.value.images = ''
  // 1. 重置查询参数为初始值
  data.queryParams = {
    pageNum: 1,
    pageSize: 10,
    routeId: null,
    communityId: null,
    patrollerName: null,
    patrollerPhone: null,
    patrolTime: null,
    patrolResult: null,
    status: null,
    images: null,
    description: null,
  };
  // 2. 重置查询表单的校验状态（如果有校验规则）
  if (queryRef.value) {
    queryRef.value.resetFields();
  }
  // 3. 重新查询
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.patrolId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加patrol"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _patrolId = row.patrolId || ids.value
  getPatrol(_patrolId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改patrol"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["patrolRef"].validate(valid => {
    if (valid) {
      if (form.value.patrolId != null) {
        updatePatrol(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          console.log(form.value)
          getList()
        })
      } else {
        addPatrol(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
    console.log(form.value)
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _patrolIds = row.patrolId || ids.value
  proxy.$modal.confirm('是否确认删除patrol编号为"' + _patrolIds + '"的数据项？').then(function () {
    return delPatrol(_patrolIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/patrol/export', {
    ...queryParams.value
  }, `patrol_${new Date().getTime()}.xlsx`)
}

getList()
</script>


<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>